import xmlrpclib


class rtorrent:

	# Create an object to represent our server.
	server_url = 'http://localhost';
	server = xmlrpclib.Server(server_url);

	def sizeof_fmt(self, num):
	    for x in ['bytes','KB','MB','GB','TB']:
        	if num < 1024.0:
			return "%3.1f%s" % (num, x)
			
	        num /= 1024.0

	def rate_fmt(self, num):
		return "%.2f" % (num / 1024.0)

	def time_fmt(self, secs):
		mins, secs = divmod(secs, 60)
		hours, mins = divmod(mins, 60)

		return '%02d:%02d:%02d' % (hours, mins, secs)

	def get_list(self):
		result = self.server.d.multicall("incomplete", "d.get_name=", "d.get_size_bytes=", "d.get_down_total=", "d.get_down_rate=","d.get_state=", "d.get_hash=", "d.get_peers_connected=", "d.get_peers_not_connected=")
		for sum in result:
			if sum[4] == 0:
				sum[0] = '<strong>[Paused]</strong> ' + sum[0]
			if sum[1] < 0:
				sum[1] = sum[1] * -1	
			sum.append((100 * int(sum[2])) / int(sum[1])) # %
			if sum[3] > 0:
				eta = self.time_fmt(sum[1] / sum[3])
			else:
				eta = '??'
			sum.append(eta) # ETA
			sum[1] = self.sizeof_fmt(sum[1])
			sum[2] = self.sizeof_fmt(sum[2])
			sum[3] = str(self.rate_fmt(sum[3]))


		return result


	# Completed downloads list
	def get_done_list(self):
		result = self.server.d.multicall("complete", "d.get_name=", "d.get_size_bytes=", "d.get_up_rate=", "d.get_ratio=", "d.get_hash=")
		for sum in result:
			if sum[1] < 0:
				sum[1] = sum[1] * -1	
			sum[1] = self.sizeof_fmt(sum[1])
			sum[2] = self.rate_fmt(sum[2])
			sum[3] = str("%.2f" % (sum[3] / 1000.0))

		return result

	def get_download_rate(self):
		return self.rate_fmt(self.server.get_download_rate())

	def get_upload_rate(self):
		return self.rate_fmt(self.server.get_upload_rate())

	def delete_download(self, thash):
		return self.server.d.erase(thash)

	def pause_download(self, thash):
		return self.server.d.stop(thash)

	def resume_download(self, thash):
		return self.server.d.start(thash)

